from django.shortcuts import render
from . import models
from django.http import HttpResponse, HttpResponseRedirect
# 加载模板识别html文档中的变量
from django.template import loader


# Create your views here.
def add_db_view(res):
    """为数据库添加数据行"""
    if res.method == 'GET':
        # books前面不能加斜杠,不然去根目录下寻找
        return render(res, 'bookstore/add_book.html')
    elif res.method == 'POST':
        title = res.POST.get('name')
        prices = float(res.POST.get('price'))
        pubs = res.POST.get('pub')
        market_prices = float(res.POST.get('market_price'))
        # print("price",type(prices), "市场价:", type(market_prices))
        
        try:
            models.Book.objects.create(name = title, price=prices, pub = pubs, market_price=market_prices) # 提交到数据库
            return HttpResponseRedirect("/books/add")
        except Exception as e:
            return HttpResponse("添加数据行失败.")
        
        
def cha_view(res):
    """查询"""
    if res.method == "GET":
        # books前面不能加斜杠,不然去根目录下寻找
        return render(res, 'bookstore/add_book.html')
    elif res.method == "POST":
        # if res.POST.get('name_btn'):
            # 识别html中的变量
        t = loader.get_template('bookstore/add_book.html')
        
        books = models.Book.objects.all()
        for i in books:
            html = t.render({'cha_xun': i.name, 'cha_xun1':i.price,'cha_xun1':i.pub,'cha_xun1':i.market_price})
        
            return HttpResponse(html)
        

def show_all(res):
    """从数据库查询到的数据显示到table列表中!"""
    booksc = models.Book.objects.all()
    # 如果需要安装条件查找在大于,小于,大于等于,小于等于符号不能用>,<,>=,<=符号, 详情转 Django教程day04.md
    # 需要替换Django对等的变量,即 查询谓词, __gt 是大于的意思
    # books = models.Book.objects.filter(price__gt=50)
    
    # locals() 方法自动传递 booksc 变量
    return render(res, 'bookstore/list.html', locals())

def mod_view(res, ids):
    book_id = int(ids) # ids 得到浏览器传过来的值, 前提要在路由中提取出来,否则会提示方法没有传值的错误!
    try:
        # 根据浏览器传过来的id找到数据库对应的数据条,找不到后面则都没有意义了
        abook = models.Book.objects.get(id=book_id) 
    except Exception as e:
        return HttpResponse("没有找到id为:", id + "的数据记录", e)

    if res.method == 'GET':
        return render(res, 'bookstore/mod.html', locals())
    elif res.method == 'POST':
        m_price = res.POST.get('market_price') # 获取浏览器传过来的值
        abook.market_price = m_price # 修改字段的值,也就是修改价格
        abook.save() # 执行修改操作
    
        return HttpResponseRedirect('/books/list') # 重定向, 返回到列表页面
    # 只接受GET和POST两个请求,否则返回错误
    return HttpResponse("鸭儿了嘿....")

def del_view(res, ids):
    """删除数据条"""
    
    try:
        abook = models.Book.objects.get(id=int(ids))
    except Exception:
        print("数据库没有这条数据")
        return HttpResponse("删除失败!")
    
    if res.method == 'GET':
        abook.delete()
        print('GET请求, 删除成功!')
        return HttpResponseRedirect('/books/list')
    return HttpResponse("鸭儿了嘿...") 